package cn.tqfeiyang.smartadmin.business.organization.service;

import cn.tqfeiyang.smartadmin.business.organization.mapper.DepartmentMapper;
import cn.tqfeiyang.smartadmin.business.organization.entity.DepartmentEntity;

import cn.tqfeiyang.smartadmin.commons.mybatis.IEntityCache;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.*;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import jakarta.annotation.Resource;

import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 部门缓存服务
 *
 * @author tqfeiyang
 * @since 2024-10-18
 */
@Service
@Slf4j
public class DepartmentCacheService implements IEntityCache<DepartmentEntity> {

    /**
     * 部门列表缓存
     */
    private static final String DEPARTMENT_LIST_CACHE = "business:organization:department:list";

    /**
     * 部门map缓存
     */
    private static final String DEPARTMENT_MAP_CACHE = "business:organization:department:map";

    /**
     * 部门映射接口
     */
    @Resource
    private DepartmentMapper departmentMapper;

    /**
     * 清空部门缓存
     */
    @CacheEvict(value = {
            DEPARTMENT_LIST_CACHE,
            DEPARTMENT_MAP_CACHE}, allEntries = true)
    @Override
    public void clearCache() {
        log.info("清空部门缓存");
    }

    /**
     * 查询部门列表
     *
     * @return 部门列表
     */
    @Cacheable(DEPARTMENT_LIST_CACHE)
    public List<DepartmentEntity> getDepartmentList() {
        return departmentMapper.selectList(Wrappers.emptyWrapper());
    }

    /**
     * 查询部门map
     *
     * @return 部门map
     */
    @Cacheable(DEPARTMENT_MAP_CACHE)
    public Map<Long, DepartmentEntity> getDepartmentMap() {
        return getDepartmentList().stream()
                .collect(Collectors.toMap(DepartmentEntity::getDepartmentId, Function.identity()));
    }

    /**
     * 根据部门id查询部门信息
     *
     * @param departmentId 部门id
     * @return 部门信息，如果不存在则返回null
     */
    public DepartmentEntity findDepartmentByDepartmentId(Long departmentId) {
        Assert.notNull(departmentId, "departmentId不能为空");
        return getDepartmentMap().get(departmentId);
    }
}
